package org.idea.spring.ioc;

import org.idea.spring.ioc.bean.Person;
import org.idea.spring.ioc.config.Sex;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Map;

/**
 * 依赖查找 案例
 *  按照bean的名称 类型 注解进行查找 查找结果分为：单个bean，多个bean
 *
 * @Author idea
 * @Date created in 10:33 下午 2020/4/30
 */
public class IocLookupDemo {

    public static void main(String[] args) {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("META-INF/bean-ioc.xml");
        lookupInRealTime(beanFactory);
        lookupLazyTime(beanFactory);
        lookupByType(beanFactory);
        lookupByList(beanFactory);
        lookupByAnnotation(beanFactory);
    }

    /**
     * 按照注解方式获取bean对象
     *
     * @param beanFactory
     */
    private static void lookupByAnnotation(BeanFactory beanFactory) {
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, Person> map  = (Map) listableBeanFactory.getBeansWithAnnotation(Sex.class);
            System.out.println(map);
        }
    }

    /**
     * 查找list集合类型的bean
     */
    private static void lookupByList(BeanFactory beanFactory){
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String,Person> personMap = listableBeanFactory.getBeansOfType(Person.class);
            System.out.println(personMap);
        }
    }

    /**
     * 按照类型查询bean
     * @param beanFactory
     */
    private static void lookupByType(BeanFactory beanFactory){
        Person person = beanFactory.getBean(Person.class);
        System.out.println(person.toString());
    }

    /**
     * 延迟查找
     *
     * @param beanFactory
     */
    private static void lookupLazyTime(BeanFactory beanFactory){
        //这个时候bean并没有被赋值
        ObjectFactory<Person> objectFactory = (ObjectFactory<Person>) beanFactory.getBean("objectFactory");
        //这里调用了getObject的时候才会被创建
        Person person = objectFactory.getObject();
        System.out.println(person.toString());
    }

    /**
     * 实时获取bean相关信息
     */
    private static void lookupInRealTime(BeanFactory beanFactory) {
        Person person = (Person) beanFactory.getBean("person");
        System.out.println(person.toString());
    }
}
